import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import 'rxjs/add/operator/map';

import { login } from '../utils/api';

@Injectable()
export class LoginService {
  isLogin = false;
  username = '';

  constructor(public http: Http, public router: Router) { }

  login(user) {
    return this.http.post(login.query, user)
      .map(res => {
        console.log('res', res);
        return res.json();
      });
  }

  loginOut() {
    window.localStorage.clear();
    this.router.navigate(['/login']);
    this.isLogin = false;
  }

  logInit() {
    const userinfo = window.localStorage.getItem('userinfo');
    if (userinfo) {
      const user = JSON.parse(userinfo);
      this.username = user.username;
      this.isLogin = true;
    } else {
      this.username = '';
      this.isLogin = false;
    }
  }

}
